import { PrismaClient } from '@prisma/client';
import { randomUUID } from 'crypto';

enum UserRoleType {
  NORMAL = 'NORMAL', /// 普通用户
  VIP = 'VIP', /// VIP用户
  SVIP = 'SVIP', /// SVIP用户
}

const prisma = new PrismaClient();

async function main() {
  // 按顺序生成角色
  await prisma.userRole.upsert({
    where: { role: UserRoleType.NORMAL },
    update: { refreshPoint: +process.env.NORMAL_POINTS },
    create: { role: UserRoleType.NORMAL, refreshPoint: +process.env.NORMAL_POINTS },
  });
  await prisma.userRole.upsert({
    where: { role: UserRoleType.VIP },
    update: { refreshPoint: +process.env.VIP_POINTS },
    create: { role: UserRoleType.VIP, refreshPoint: +process.env.VIP_POINTS },
  });
  await prisma.userRole.upsert({
    where: { role: UserRoleType.SVIP },
    update: { refreshPoint: +process.env.SVIP_POINTS },
    create: { role: UserRoleType.SVIP, refreshPoint: +process.env.SVIP_POINTS },
  });

  // 生成卡密
  const vipRole = await prisma.userRole.findUnique({ where: { role: UserRoleType.VIP } });
  const svipRole = await prisma.userRole.findUnique({ where: { role: UserRoleType.SVIP } });

  if (!vipRole || !svipRole) {
    throw new Error('VIP 或 SVIP 角色不存在');
  }

  // 检查现有卡密数量
  const existingCount = await prisma.cardKey.count({ where: { isUsed: false } });
  const targetTotal = +process.env.INIT_CARD_KEY_COUNT * 2; // VIP + SVIP
  const needToAdd = Math.max(0, targetTotal - existingCount);

  console.log('needToAdd', needToAdd);

  if (needToAdd > 0) {
    // 需要生成的数量（一半VIP，一半SVIP）
    const halfCount = Math.ceil(needToAdd / 2);

    // 生成 VIP 卡密
    const vipKeys = Array.from({ length: halfCount }, () => ({
      key: randomUUID(),
      usedRoleId: vipRole.id,
      duration: 30,
    }));

    // 生成 SVIP 卡密
    const svipKeys = Array.from({ length: needToAdd - halfCount }, () => ({
      key: randomUUID(),
      usedRoleId: svipRole.id,
      duration: 30,
    }));

    await prisma.cardKey.createMany({
      data: [...vipKeys, ...svipKeys],
    });
  }
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(() => {
    prisma.$disconnect();
    console.log('================================================ Seed Done ================================================');
  });
